<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    /**
     * 创建文章
     * @param $request \Request 请求数据
     * @return bool
     * */
    public function create($request)
    {
        $this->title = $request->title;
        $this->cate = $request->cates_str;
        $this->user_name = $request->user_name;
        $this->user_id = $request->user_id;
        $this->content = $request->content;
        $this->cate_id = $request->cates_id;
        return $this->save();
    }

    /**
     * 更新文章
     * */
    public function edit($request)
    {
        $article = $this->find($request->id);
        $article->title = $request->title;
        $article->cate = $request->cates_str;
        $article->content = $request->content;
        $article->cate_id = $request->cates_id;
        return $article->save();
    }

    /**
     *
     * @param int $page 每页显示数据数量
     * @param array $condition 查询条件
     * @return object
     * */
    public function getList($page, array $condition = [])
    {
        return $this->where($condition)->paginate($page);
    }

    /*
     * 前台显示整理数据
     * */
    public function getBlogList($page, array $condition = [])
    {
        $articles = $this->getList($page, $condition);
        foreach ($articles as $key => $article) {
            $articles[$key]->cate_arr = unserialize($article['cate']);
            $articles[$key]->description = $this->cutArticle($article['content'], 150);
        }
        return $articles;
    }

    /*
     * 截取摘要
     * */
    protected function cutArticle($data,$cut=0,$str="....")
    {

        $data=strip_tags($data);//去除html标记
        $pattern = "/&[a-zA-Z]+;/";//去除特殊符号
        $data=preg_replace($pattern,'',$data);
        if(!is_numeric($cut))
            return $data;
        if($cut>0)
            $data=mb_strimwidth($data,0,$cut,$str);
        return $data;
    }

    public function getInfo($id)
    {
        $article_info = $this->find($id);
        $article_info->cate_arr = unserialize($article_info['cate']);
        return $article_info;
    }

    /*
     * 删除
     * */
    public function del($id)
    {
        return self::destroy($id);
    }
}
